<?php
class Admin_CommentsController extends Zend_Controller_Action
{
	public $filters=array('id'=>array('HtmlEntities','StripTags','StringTrim'));
	public $validators=array('id'=>array('NotEmpty','Int'));
	public $filters2=array('aid'=>array('HtmlEntities','StripTags','StringTrim'));
	public $validators2=array('aid'=>array('NotEmpty'));

	public function preDispatch()
	{}
    public function init()
    {
        if($this->getRequest()->isXmlHttpRequest()){
          //  $this->_helper->getHelper('layout')->disableLayout();
        }
    }
	public function indexAction()
	{
	$filters=array('id'=>array('HtmlEntities','StripTags','StringTrim'));
	$validators=array('id'=>array('NotEmpty'));
	$input=new Zend_Filter_Input($filters,$validators);
	$input->setData($this->getRequest()->getParams());
		if($input->isValid()){
	$q=Doctrine_Query::create()
		->from('Myblog_Model_Comments c')
		->leftJoin('c.Myblog_Model_Articles a')
		->where('c.article_id=?',$input->id);
        //->useResultCache(true);
		$result=$q->fetchArray();
		if(!empty($result))
		{
		$this->view->title=$result[0]['Myblog_Model_Articles']['title'];
		$this->view->comments=$result;
		$select=new Myblog_Form_Visibility;
		$select->visibility->options['yes']='Да';
		$select->visibility->options['no']='Нет';
		$this->view->select=$select;
				if($this->getRequest()->isPost() && $select->isValid($this->getRequest()->getPost()))
				{
				
				$data=$this->getRequest()->getPost();
				$q=Doctrine::getTable('Myblog_Model_Comments')
					->find($data['id']);
				$q->fromArray($data);
				$q->save();
				}
			}else{
					$this->_helper->getHelper('FlashMessenger')
						->addMessage('Комментарии к этой статье не существует');
						$this->_redirect('/admin/comments/save/success/');
				 }
		}
	}
 
	public function editAction()
	{
	$form=new Myblog_Form_CommentsEdit;
	$this->view->form=$form;
		if($this->getRequest()->isPost() )
		{
		$data=$this->getRequest()->getPost();
			if(!empty($data))
			{
			//$data['created_time']=ltrim($data['created_time'],'T');
			//$data['created_dt']=$data['created_date'].' '.$data['created_time'];
		$q=Doctrine::getTable('Myblog_Model_Comments')
			->find($data['idn']);
		$q->fromArray($data);
		$q->save();
		$this->_helper->getHelper('FlashMessenger')
			->addMessage('Комментарий успешно обновлен');
		$this->_redirect('/admin/comments/save/success/');
			}
		}
		else{
	$filters=array('id'=>array('HtmlEntities','StripTags','StringTrim'));
	$validators=array('id'=>array('NotEmpty'));
	$input=new Zend_Filter_Input($filters,$validators);
	$input->setData($this->getRequest()->getParams());
	if($input->isValid()){
	$q=Doctrine_Query::create()
		->from('Myblog_Model_Comments c')
		->where('c.id=?',$input->id);
	$result=$q->fetchArray();
	$result[0]['created_date']=substr($result[0]['created_dt'],0,-9);
	$time=substr($result[0]['created_dt'],11);
	$result[0]['idn']=$input->id;
	$result[0]['created_time']='T'.$time;

	$this->view->form->populate($result[0]);
		}
	}
  }
	public function deleteAction()
	{
		$input=new Zend_Filter_Input($this->filters,$this->validators);//принимаем  id комментария для удаления коммента
		$input2=new Zend_Filter_Input($this->filters2,$this->validators2);//принимаем id статьи для редиректа обратно на страницу статьи
		$input->setData($this->getRequest()->getParams());
		$input2->setData($this->getRequest()->getParams());
		
		if($input->isValid() && $input2->isValid())
		{
		$q=Doctrine::getTable('Myblog_Model_Comments')
			->find($input->id)
			->delete();
		$this->_helper->getHelper('FlashMessenger')
			->addMessage('Комментарий успешно удален');
				
			$this->_redirect('/admin/comments/save/success/');
		}
	}
	public function allcommentsAction()
        /**
         * jQuery plugin: jquery.comments.js
         * URI :/admin/allcomments
         */
	    {
	       $q = Doctrine_Query::create()
               ->from('Myblog_Model_Comments c')
               ->leftJoin('c.Myblog_Model_Articles a')
                ->select('c.article_id,COUNT(c.article_id) AS commcount,a.title AS title')
                ->groupby('c.article_id')
               ->fetchArray();
            if(count($q) >0){

                $this->view->data = $q;
            }
	    }

    public function getartcommentsAction()
    {
        /**
         * jQuery plugin: jquery.comments.js
         * URI :/admin/getartcomments
         * не используется
         */
        $artid = $this->getRequest()->getParam('id');
        $limit = $this->getRequest()->getParam('limit');
        $offset = $this->getRequest()->getParam('offset');

        if(!isset($limit)){$limit = 0;}
        if(!isset($offset)){$offset = 0;}
        if(isset($artid)){
            $q = Doctrine_Query::create()
                ->from('Myblog_Model_Comments c')
                ->leftJoin('c.Myblog_Model_Articles a')
                ->select('c.id,c.name,c.email,c.author_id,c.article_id,c.created_dt,c.role,c.blog_comment,c.visibility,a.title AS title')
                ->where('c.article_id=?',$artid)
                ->offset($offset)
                ->limit($limit)
                //->useResultCache(true)
                ->fetchArray();

            for($i=0;$i <count($q);$i++){
                $q[$i]['count'] = count($q);

                if($q[$i]['role']=='user'){
                    $av=Doctrine_Query::create()
                    ->from('Myblog_Model_Users u')
                    ->select('u.avatar')
                    ->where('u.id=?',$q[$i]['author_id'])
                   // ->useResultCache(true)
                    ->fetchArray();
                    $q[$i]['avatar']=$av[0]['avatar'];

                }
            }
            $this->view->comments = $q;
            $this->view->title =  $q[0]['title'];
            $this->view->artid =  $artid;

            //$this->_helper->json($q);
        }
    }
    public function getCommentsAction()
    {
            $q = Doctrine_Query::create()
                ->from('Myblog_Model_Comments c')
                ->leftJoin('c.Myblog_Model_Articles a')
                ->select('c.id,c.name,c.email,c.author_id,c.article_id,c.created_dt,c.role,c.blog_comment,c.visibility,a.title AS title')
                ->fetchArray();

            for($i=0;$i <count($q[$i]['author_id']);$i++){
                $q[$i]['count'] = count($q);

                if($q[$i]['role']=='user'){
                $av=Doctrine_Query::create()
                    ->from('Myblog_Model_Users u')
                    ->select('u.avatar')
                    ->where('u.id=?',$q[$i]['author_id'])
                    //->useResultCache(true)
                    ->fetchArray();
                    $q[$i]['avatar']=$av[$i];
                }
            }
            $this->_helper->json($q);
    }

    public function commentUpdateAction(){
        if($this->getRequest()->isXmlHttpRequest())
            {
                $this->_helper->getHelper('layout')->disableLayout();
                $post = $this->getRequest()->getPost();

                $q = Doctrine_Query::create()
                    ->update('Myblog_Model_Comments c')
                    ->set('c.blog_comment','?',$post['blog_comment'])
                    ->where('c.id=?',$post['id'])
                    ->execute();

                if($q){
                    $this->_helper->json(array("oper"=>"update_success"));
                }else{
                    $this->_helper->json(array("oper"=>"unchanged"));
                }

            }
    }
    public function commentVisibilityAction(){
        if($this->getRequest()->isXmlHttpRequest())
            {
            $this->_helper->getHelper('layout')->disableLayout();
            $post = $this->getRequest()->getPost();
            $q = Doctrine_Query::create()
                    ->update('Myblog_Model_Comments c')
                    ->where('c.id=?',$post['id'])
                    ->set('c.visibility','?',$post['visibility'])
                    ->execute();
                if($q){
                    $this->_helper->json(array("oper"=>"yes"));
                }else{
                    $this->_helper->json(array("oper"=>"no"));
                }
            }
    }
    public function commentDeleteAction(){

            $this->_helper->getHelper('layout')->disableLayout();
            $post = $this->getRequest()->getPost();
            if(isset($post['id']) && isset($post['artid'])){
                $del = Myblog_Model_Users::del($post,'Myblog_Model_Comments','article_id');
            }else{
                $del = Myblog_Model_Users::del($post,'Myblog_Model_Comments','id');
            }
            if($del){$this->_helper->json(array('oper'=>$del));}
    }

    public function getCommentPageAction(){
        /**
         * jQuery plugin: jquery.comments.js
         * URI :/admin/comments/getpage
         */

        $pageId = $this->getRequest()->getParam('id');
        $artid = $this->getRequest()->getParam('artid');
        $pageLimit = $this->getRequest()->getParam('limit');
        $offset = ($pageId*5)-5;//5

        if(isset($pageId) && isset($pageLimit)){
            $q = Doctrine_Query::create()
                ->from('Myblog_Model_Comments c')
                ->where('c.article_id=?',$artid)
                ->offset($offset)
                ->limit($pageLimit)
                ->fetchArray();

            for($i=0;$i < count($q);$i++){
                if($q[$i]['role'] === 'admin' || $q[$i]['role'] === 'demo_admin' || $q[$i]['role'] === 'user'){
                    $av = Doctrine_Query::create()
                        ->from('Myblog_Model_Users u')
                        ->select('u.avatar')
                         ->where('u.id=?',$q[$i]['author_id'])
                        ->fetchArray();
                if(isset($av[$i]['avatar'])){
                        $q[$i]['avatar']=$av[$i]['avatar'];
                    }
                }else{
                    $q[$i]['avatar']='/images/avatars/noavatar92.png';
                }
            }
            //============================================
            $pCnt = Doctrine_Query::create()
                ->from('Myblog_Model_Comments c')
                ->where('c.article_id=?',$artid)
                ->select('COUNT(id) AS pagescount')
                ->fetchArray();
            if(isset($q[0]['title'])){
                $this->view->title =  $q[0]['title'];
            }
            $this->view->artid =  $q[0]['article_id'];
            $this->view->pages =  $pCnt[0]['pagescount'];
            $this->view->comments = $q;
        }
    }

	public function successAction()
	{
		if($this->_helper->getHelper('FlashMessenger')->getMessages()){
			$this->view->messages=$this->_helper->getHelper('FlashMessenger')->getMessages();
				//header("Refresh:3;/admin/index");
            $this->getResponse()->setHeader('Refresh','3; URL=/admin/index');
		}
        else{
			$this->redirect('/admin/comments/index/'.$input2->aid);
		    }
	}
}
